<template>
  <el-form ref="loginForm" :model="user" :rules="userRules" status-icon>
    <el-form-item prop="username">
      <el-input v-model="user.username" />
    </el-form-item>
    <el-form-item prop="password">
      <el-input type="password" v-model="user.password" show-password/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="login(loginForm)">
        登录
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">

import {ref} from "vue";
import {FormInstance, ElMessage} from "element-plus";
import { doLogin } from '../components/ajax'
import router from '../components/router'

const user = ref({
  username: '',
  password: ''
})

const userRules = ref({
  username: [
    {required: true, message: '请输入账号', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'}
  ]
})

const loginForm = ref<FormInstance>()

const login = (loginForm: FormInstance | undefined) => {
  if(!loginForm) return
  //校验
  loginForm.validate( valid => {
    if(valid){
      doLogin("/login", user.value, resp => {
        if(resp.status === 2000){
          //登录成功，路由跳转至主页面
          router.push({name: 'Manage', replace: true})
        } else if(resp.status === 4000){
          ElMessage.error("账号不存在")
        } else if(resp.status === 4001){
          ElMessage.error("账号或密码错误")
        } else if(resp.status === 4002){
          ElMessage.error("账号被禁用")
        }
      })
    } else {
      return false
    }
  })
}
</script>

<style scoped>

</style>
